<?php

use app\modules\Admin\models\dianpuapplyModel;
use app\modules\Admin\models\merchantModel;
use app\modules\Admin\models\dianpuModel;
use Illuminate\Database\Capsule\Manager as DB;

#[店铺申请管理]
class DianpuapplyController extends AcommonController {

    public function init() {
        $this->model = new dianpuapplyModel();
        $this->table = 'dianpu_apply';
        $this->primaryKey = 'id';
        parent::init();
    }
    
    #[店铺申请列表]
    public function indexAction($returnData = FALSE)
    {
        if ($this->isPost()){
            $this->model = $this->model->with(['member']);
            $mode = $this->get('mode', 'all');
            $post_data = $this->postData;
            switch ($mode){
                case 'reject':
                    array_push($this->search,['status', '=', -1]);
                    break;
                case 'waiting':
                    array_push($this->search,['status', '=', 0]);
                    break;
                case 'accepted':
                    array_push($this->search,['status', '=', 1]);
                    break;
            }
            if(isset($post_data['dianpuapply_start']) && !empty($post_data['dianpuapply_start'])){
                $this->model = $this->model->whereDate('created_at', '>=', $post_data['dianpuapply_start']);
            }
            if(isset($post_data['dianpuapply_end']) && !empty($post_data['dianpuapply_end'])){
                $this->model = $this->model->whereDate('created_at', '<=', $post_data['dianpuapply_end']);
            }
            $keywordsTypeArray = [
                'user_id' => 'user_id',
                'user_phone' => 'user_phone',
            ];
            if(isset($post_data['keywordsType']) && isset($post_data['keywords'])
                && in_array($post_data['keywordsType'], $keywordsTypeArray)
                && !empty($post_data['keywords'])){
                if($post_data['keywordsType'] == $keywordsTypeArray['user_id'] && is_numeric($post_data['keywords']) && intval($post_data['keywords']) > 0){
                    array_push($this->search, ['member_id', '=', $post_data['keywords']]);
                }
                if($post_data['keywordsType'] == $keywordsTypeArray['user_phone']){
                    if(mb_strlen($post_data['keywords'], 'utf-8') < 4){
                        array_push($this->search, ['id', '=', 0]);
                    }else{
                        array_push($this->condition_in, ['member_id', memberModel::query()->where('phone', 'like', "%{$post_data['keywords']}%")->pluck('id')->toArray()]);
                    }
                }
            }
            unset($keywordsTypeArray);
        }else{
            $this->_view->assign('all_status', json_encode(['all'=>'全部',
                'reject' => '驳回',
                'waiting'  => '未审核',
                'accepted'  => '已通过'
            ], JSON_UNESCAPED_UNICODE));
        }
        return parent::indexAction($returnData); // TODO: Change the autogenerated stub
    }

    #[店铺申请详情]
    public function viewAction($returnData = FALSE)
    {
        $id = $this->get('id', 0);
        try {
            $apply = dianpuapplyModel::with(['member', 'dianpu'])->findOrFail($id);
            $apply->reason_user_name = '';
            if($apply->reason_user){
                $apply->reason_user_name = adminModel::query()->where('id', $apply->reason_user)->value('username');
            }
            $this->_view->assign('dataset', json_encode($apply, JSON_UNESCAPED_UNICODE));
            $this->_view->display( strtolower($this->controller) . '/view.html');
        }catch (Exception $e){
            ret(3001, $e->getMessage());
        } finally {
            unset($id);
        }
    }

    #[申请图片查看]
    public function showpicAction()
    {
        $id = $this->get('id', 0);
        try {
            $apply = dianpuapplyModel::findOrFail($id);
            $mode = $this->get('mode', 0);
            switch ($mode){
                case 0:
                    $image = $apply->company_license_image;
                    break;
                case 1:
                    $image = $apply->company_representative_idcard_front_image;
                    break;
                case 2:
                    $image = $apply->company_representative_idcard_reverse_image;
                    break;
                case 3:
                    $image = $apply->company_representative_idcard_hand_image;
                    break;
                default:
                    $image = '';
            }
            if(!empty($image)){
                $this->_view->assign('img', $image);
                $this->_view->display( strtolower($this->controller) . '/showpic.html');
            }else{
                throw new Exception('图片地址不存在');
            }
        }catch (Exception $e){
            throw new Exception('申请不存在');
        }
    }

    #[设置店铺申请代理费用]
    public function feeeditAction()
    {
        $id = $this->get('id', 0);
        try {
            $apply = $this->model->with('member')->findOrFail($id);
            if ($this->isPost()){
                $params = $this->postData;
                if(!is_numeric($params['agent_fee']) || $params['agent_fee'] <= 0){
                    ret(11, '代理费用非法或小于0');
                }
                $res   = DB::transaction(function () use ($apply, $params) {
                    $apply->agent_fee = $params['agent_fee'];
                    $apply->agent_fee_pay_status = $params['agent_fee_pay_status'];
                    $apply->agent_fee_payed_id = $params['agent_fee_payed_id'];
                    $apply->updated_at = timestamp();
                    return $apply->save();
                });
                if($res){
                    ret(0, '恭喜，代理费及支付设置成功！');
                }else{
                    ret(1, '抱歉，代理费及支付设置失败！');
                }
            }else{
                $this->_view->assign('dataset', $apply->toJson());
                $this->_view->display( strtolower($this->controller) . '/feeedit.html');
            }
        }catch (Exception $e){
            if($this->isPost()){
                ret(1, '代理申请不存在');
            }else{
                throw new Exception('代理申请不存在');
            }
        } finally {
            unset($id, $apply);
        }
    }

    #[获取用户有效订单]
    public function getorderAction()
    {
        $id = $this->get('id', 0);
        if($this->isPost()){
            $params = $this->postData;
            $query = \orderModel::query()->with(['member', 'item'])->where('member_id', $id)->where('status', '>','0')->whereNotExists(function ($query) {
                $query->from('order_item')->whereColumn('order_item.order_id', 'order.id')
                      ->where('refund_status', '>', 0);
            })->where(function ($query){
                $query->whereNull('deleted_at')->orWhereDate('deleted_at', '>', '0000-00-00');
            })->orderByDesc('created_at');
            $start_on     = $params['start_on'];
            $end_on       = $params['end_on'];
            $keywordsType = $params['keywordsType'];
            $keywords     = $params['keywords'] ?? '';
            if (!empty($start_on)) {
                $query = $query->whereDate('created_at', '>=', $start_on);
            }
            if (!empty($end_on)) {
                $query = $query->whereDate('created_at', '<=', $end_on);
            }
            if (!empty($keywords)) {
                switch ($keywordsType) {
                    case 'order_id':
                        $query = $query->where('id', $keywords);
                        break;
                    case 'order_sn':
                        $query = $query->where('order_sn', 'like', "%{$keywords}%");
                        break;
                    case 'member_id':
                        $query = $query->where('member_id', $keywords);
                        break;
                    case 'member_phone':
                        $query = $query->whereIn('member_id', DB::table('member')->where('phone', 'like', "%{$keywords}%")->limit(20)->pluck('id'));
                        break;
                    case 'customer_id':
                        $query = $query->where('customer_id', $keywords);
                        break;
                    case 'consignee':
                        $query = $query->where('consignee', $keywords);
                        break;
                    case 'consignee_phone':
                        $query = $query->where('phone', 'like', "%{$keywords}%");
                        break;
                }
            }

            $page = $this->get('page', 1);
            if (!empty($page)) {
                $limit = $this->get('rows', 10);
                $offset = ($page - 1) * $limit;
                $query = $query->offset($offset)->limit($limit);
            }
            $orderList = $query->get()->append('status_name')->toArray();
            json(['total' => count($orderList), 'rows' => $orderList]);
        }else{
            $this->_view->assign('id', $id);
            $this->_view->display( strtolower($this->controller) . '/getorder.html');
        }
    }

    #[删除店铺申请]
    public function deleteAction()
    {
        if ($this->isPost()){
            $id = $this->get('id', 0);
            try{
                $dianpuApply = $this->model->findOrFail($id);
                if($dianpuApply->status === 1){
                    if (dianpuModel::withTrashed()->where('apply_id', $id)->exists()){
                        ret('2', '删除失败，此申请已经通过<br>如确定要删除，请先 [删除并销毁店铺] 后再进行删除操作！');
                    }
                }
            }catch (Exception $e){
                ret(1, '店铺申请不存在');
            } finally {
                unset($id);
            }
            parent::deleteAction(); // TODO: Change the autogenerated stub
        }else{
            ret(2000, '请求出错！');
        }
    }

    #[同意店铺申请]
    public function applysuccessAction()
    {
        if($this->isPost()){
            $opt_id = $this->postData['id'];
            try {
                $applyModel = $this->model->findOrFail($opt_id);
                if($applyModel->status !== 0){
                    throw new Exception('申请已经处理过，不能重复处理！', 30001);
                }
                if(merchantModel::query()->where('member_id', $applyModel->member_id)->exists()){
                    throw new Exception('您已经拥有店铺或是店铺的管理员，不能成为店铺代理！', 30001);
                }
                $member = memberModel::query()->where('id', $applyModel->member_id)->first();
                if(!$member){
                    throw new Exception('申请用户不存在', 30001);
                }
                if($member->status !== 'normal'){
                    throw new Exception('申请用户非正常状态', 30001);
                }
                if(empty($member->phone)){
                    throw new Exception('申请用户未绑定手机号', 30001);
                }
                if(empty($member->password)){
                    throw new Exception('申请用户未设置登录密码', 30001);
                }
                $res = DB::transaction(function () use ($applyModel) {
                    $applyModel->status = 1;
                    $applyModel->updated_at = timestamp();
                    if($applyModel->save()){
                        $created_at = timestamp();
                        $dianpu_id = dianpuModel::query()->insertGetId([
                                                'name' => $applyModel->name,
                                                'company_name' => $applyModel->company_name,
                                                'company_representative_name' => $applyModel->realname,
                                                'phone' => $applyModel->phone,
                                                'province_name' => $applyModel->province_name,
                                                'city_name' => $applyModel->city_name,
                                                'area_name' => $applyModel->area_name,
                                                'province_id' => $applyModel->province_id,
                                                'city_id' => $applyModel->city_id,
                                                'area_id' => $applyModel->area_id,
                                                'address' => $applyModel->address,
                                                'apply_id' => $applyModel->id,
                                                'status' => 1,
                                                'created_at' => $created_at,
                                                'updated_at' => $created_at,
                                                     ]);
                        merchantModel::query()->insert([
                                                        'dianpu_id'=> $dianpu_id,
                                                        'member_id'=> $applyModel->member_id,
                                                        'is_root'=> 1,
                                                        'roles_id'=> 1,
                                                        'created_at'=> $created_at,
                                                        'updated_at'=> $created_at,
                                                         ]);
                        return $dianpu_id;
                    }else{
                        return false;
                    }
                });
                if($res){
                    ret(0, '恭喜，同意店铺申请成功！');
                }else{
                    throw new Exception('抱歉，店铺申请操作失败！', 30001);
                }
            }catch (Exception $exception){
                ret(2, (($exception->getCode() === 30001)? $exception->getMessage():'操作失败，申请记录不存在或已处理！'));
            }
            unset($applyModel);
            unset($opt_id);
        }else{
            ret(500, '请求失败，非正常请求！');
        }
    }

    #[拒绝店铺申请]
    public function applyrefuseAction()
    {
        if($this->isPost()){
            $opt_id = $this->postData['id'];
            $remark = $this->postData['remark']?:'无';
            try {
                $apply = $this->model->findOrFail($opt_id);
                if($apply->status !== 0){
                    ret(5, '申请已经处理过，不能重复处理！');
                }
                $user = memberModel::find($apply->member_id);
                if(!$user){
                    ret(4, '操作失败，申请的用户不存在！');
                }
                $res = DB::transaction(function () use ($apply, $remark, $user) {
                    $apply->status = -1;
                    $apply->reason = $remark;
                    $apply->reason_user = $this->auth->user_id;
                    $apply->reason_time = timestamp();
                    $apply->updated_at = timestamp();
                    return $apply->save();
                });
                if($res){
                    ret(0, '恭喜，拒绝店铺申请操作成功！');
                }else{
                    ret(1, '抱歉，店铺申请操作失败！');
                }
            }catch (Exception $e){
                ret(2, '操作失败，申请记录不存在或已处理！');
            } finally {
                unset($opt_id, $remark, $apply, $user, $res);
            }
        }else{
            ret(500, '请求失败，非正常请求！');
        }
    }
}
